<template>
    <el-card class="table-panel">
        <!-- operation-panel -->
        <el-row v-if="tableConfig?.headerButtons?.length > 0" justify="end" class="operation-panel">
            <el-button v-for="item in tableConfig?.headerButtons" :key="item.eventKey" v-bind="item" @click="operationHandler({ btnConfig: item })">
                {{ item.label }}</el-button>
        </el-row>
        <!-- schema-tabel (组件 widget) -->
        <schema-table ref="schemaTableRef" :schema="tableSchema" :api="api" :buttons="tableConfig?.rowButtons ?? []"
            :apiParams="apiParams" @operate="operationHandler"></schema-table>
    </el-card>
</template>

<script setup>
import { ref, inject } from 'vue'
import SchemaTable from '$widget/schema-table/schema-table.vue'
import $curl from '$common/curl.js'
import { ElMessageBox, ElNotification } from 'element-plus'

const emit = defineEmits(['operate'])
const {
    api,
    tableSchema,
    tableConfig,
    apiParams
} = inject('schemaViewData')

const schemaTableRef = ref(null)

const EventHandlerMap = {
    remove: removeData
}

function removeData ({ btnConfig, rowData }) {
    const { eventOption } = btnConfig;
    if (!eventOption?.params) { return; }

    const { params } = eventOption;
    const removeKey = Object.keys(params)[0];
    // 修复未定义变量错误，正确获取参数值
    const removeValue = params[removeKey];
    const removeValueList = removeValue.split('::');

    // 添加参数格式校验
    if (removeValueList.length < 2 || removeValueList[0] !== 'schema') {
        ElNotification.error('参数格式错误，请检查配置');
        return;
    }

    const [type, field] = removeValueList;
    const actualValue = rowData[field];
    if (actualValue === undefined) {
        ElNotification.error(`数据中不存在字段: ${field}`);
        return;
    }

    ElMessageBox.confirm(
        `确认删除 ${removeKey} 为: ${actualValue} 数据?`,
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        schemaTableRef.value?.showLoading();
        const res = await $curl({
            method: 'delete',
            url: api.value,
            data: {
                [removeKey]: actualValue
            },
            errorMessage: '删除失败'
        });
        schemaTableRef.value?.hideLoading();

        if (!res || !res.success || !res.data) {
            return
        }

        ElNotification({
            title: '删除成功',
            message: `删除数据成功`,
            type: 'success'
        })

        await initTableData()
    });
};

const operationHandler = ({ btnConfig, rowData }) => {
    const { eventKey } = btnConfig
    if (EventHandlerMap[eventKey]) {
        EventHandlerMap[eventKey]({ btnConfig, rowData })
    } else {
        emit('operate', { btnConfig, rowData })
    }
}

const initTableData = async () => {
    await schemaTableRef.value?.initData();
}

const loadTableData = async () => {
    await schemaTableRef.value?.loadTableData();
}

defineExpose({
    loadTableData
})
</script>

<style scoped lang="less">
.table-panel {
    flex: 1;
    .operation-panel {
        margin-bottom: 10px;
    }
}
:deep(.el-card__body) {
    height: 98%;
    display: flex;
    flex-direction: column;
}
</style>
